/**
 * contactdepartment控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.entity.Contact;
import com.sxf.crm.entity.ContactDepartment;
import com.sxf.crm.entity.Department;
import com.sxf.crm.exception.ResourceNotFoundException;
import com.sxf.crm.service.ContactDepartmentService;
import com.sxf.crm.service.ContactService;
import com.sxf.crm.service.DepartmentService;

import lombok.RequiredArgsConstructor;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/contact-departments")
@RequiredArgsConstructor
public class ContactDepartmentController {

    private final ContactDepartmentService contactDepartmentService;
    private final ContactService contactService;
    private final DepartmentService departmentService;

    @PostMapping
    @PreAuthorize("hasAuthority('contact:edit')")
    public ResponseEntity<ContactDepartment> create(
            @RequestParam Long contactId,
            @RequestParam Long departmentId) {
        Contact contact = contactService.getContact(contactId);
        if (contact == null) {
            throw new ResourceNotFoundException("Contact not found with id: " + contactId);
        }
        Department department = departmentService.getDepartment(departmentId)
                .orElseThrow(() -> new ResourceNotFoundException("Department not found with id: " + departmentId));
        
        ContactDepartment created = contactDepartmentService.createContactDepartment(contact, department);
        return ResponseEntity.ok(created);
    }

    @GetMapping("/by-contact/{contactId}")
    @PreAuthorize("hasAuthority('contact:view')")
    public ResponseEntity<List<ContactDepartment>> getByContactId(@PathVariable Long contactId) {
        return ResponseEntity.ok(contactDepartmentService.getByContactId(contactId));
    }

    @GetMapping("/by-department/{departmentId}")
    @PreAuthorize("hasAuthority('contact:view')")
    public ResponseEntity<List<ContactDepartment>> getByDepartmentId(@PathVariable Long departmentId) {
        return ResponseEntity.ok(contactDepartmentService.getByDepartmentId(departmentId));
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('contact:edit')")
    public ResponseEntity<Void> delete(
            @RequestParam Long contactId,
            @RequestParam Long departmentId) {
        contactDepartmentService.deleteContactDepartment(contactId, departmentId);
        return ResponseEntity.noContent().build();
    }
}
